import useSyncState from "@/hooks/use-sync-state";
import { useUserStore } from "@/stores/global/user";
import { antdUtils } from "@/utils/antd";
import { t } from "@/utils/i18n";
import { useInViewport, useRequest } from "ahooks";
import {
  Button,
  Col,
  DatePicker,
  Flex,
  Form,
  Popconfirm,
  Row,
  Select,
  Space,
  Table,
  TablePaginationConfig,
} from "antd";
import { ColumnsType } from "antd/es/table";
import dayjs from "dayjs";
import { useEffect, useRef } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { useImmer } from "use-immer";
import { EditDialog, NewDialog } from "../new-edit-plan";
import myService from "../service";

const MyProjectPlan = () => {
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const ref = useRef(null);
  const [inViewport] = useInViewport(ref);
  const { currentUser } = useUserStore();
  const location = useLocation();
  const [myList, setMyList] = useImmer<any[]>([]);
  const [allUsers, setAllUsers] = useImmer<any[]>([]);
  const [showEditDialog, setShowEditDialog] = useImmer({
    isShow: false,
    data: null,
  });
  const [showNewDialog, setShowNewDialog] = useImmer(false);
  const { runAsync: getAllUser } = useRequest(myService.getAllUser, {
    manual: true,
  });
  const [pData, setPData] = useSyncState({
    id: String || null,
    name: String || null,
  });
  const [pagination, setPagination] = useImmer<TablePaginationConfig>({
    current: 1,
    pageSize: 8,
  });

  const { runAsync: findPrijectPlan } = useRequest(
    myService.getMyProjectPlans,
    {
      manual: true,
    }
  );

  const { runAsync: deleteItem } = useRequest(myService.deleteItem, {
    manual: true,
  });

  useEffect(() => {
    if (inViewport) {
      if (location.state?.id && location.state?.name) {
        setPData({ id: location.state?.id, name: location.state?.name }, () => {
          setPagination((old) => {
            old.current = 1;
          });
          getData(1);
          form.resetFields();
        });
      }
    }
  }, [location.state, inViewport]);

  const getData = async (current: number) => {
    const [error, data] = await findPrijectPlan({
      projectid: location.state?.id,
      // userid: currentUser!.id,
      page: current! - 1,
      size: pagination.pageSize,
    });
    if (error) {
      antdUtils.message?.error(error);
    } else {
      const uList: any[] = [];
      if (allUsers.length <= 0) {
        const [errorU, dataU] = await getAllUser();
        if (!errorU) {
          const list = dataU.map((user: any) => {
            return {
              value: user.id,
              label: user.nickName,
            };
          });
          setAllUsers(list);
          uList.push(...list);
        }
      } else {
        uList.push(...allUsers);
      }

      setMyList(
        (data as any).data.map((item: any) => {
          const index = uList.findIndex((e) => e.value === item.userid);
          if (index != -1) {
            item.userNickname = uList[index].label;
          }
          return item;
        })
      );
      setPagination((old) => {
        old.total = (data as any).total;
      });
    }
  };

  const tabChangeHandle = (tablePagination: TablePaginationConfig) => {
    setPagination(tablePagination);
    // getData(pData.id, tablePagination.current ? tablePagination.current : 1);
    form.submit();
  };

  const onSearch = async (value: any) => {
    let startTime, endTime;
    if (value.time) {
      startTime = dayjs(value.time[0]).format("YYYY-MM-DD");
      endTime = dayjs(value.time[1]).format("YYYY-MM-DD");
    }
    const { pageSize, current } = pagination || {};
    const [error, data] = await findPrijectPlan({
      page: (current ? current : 1) - 1,
      size: pageSize,
      id: pData.id,
      startTime: startTime,
      endTime: endTime,
      userid: value.userid,
      state: value.state,
      projectid: location.state?.id,
    });
    if (error) {
      antdUtils.message?.error(error);
      return;
    }
    setMyList(
      (data as any).data.map((item: any) => {
        const index = allUsers.findIndex((e) => e.value === item.userid);
        if (index != -1) {
          item.userNickname = allUsers[index].label;
        }
        return item;
      })
    );
    setPagination((old) => {
      old.total = (data as any).total;
    });
  };

  const columns = (): ColumnsType<any> => [
    {
      title: t("PlanName") /**计划名 */,
      dataIndex: "name",
      key: "name",
      width: 200,
      fixed: "left",
    },
    {
      title: t("personInCharge") /**负责人 */,
      dataIndex: "userNickname",
      key: "userNickname",
      width: 100,
      fixed: "left",
    },
    {
      title: t("state") /**状态 */,
      dataIndex: "state",
      key: "state",
      width: 100,
      fixed: "left",
      render: (_, item: any) => <>{getPlanState(item.state)}</>,
    },
    {
      title: t("PlannedStartTime") /**计划开始时间 */,
      dataIndex: "startTime",
      key: "startTime",
      width: 130,
      defaultSortOrder: "descend",
    },
    {
      title: t("planOverTime") /**预计完成时间 */,
      dataIndex: "planOverTime",
      key: "planOverTime",
      width: 150,
    },
    {
      title: t("executeTimeFirst") /**第一次执行时间 */,
      dataIndex: "executeTimeFirst",
      key: "executeTimeFirst",
      width: 150,
    },
    {
      title: t("overTime") /**完成时间 */,
      dataIndex: "overTime",
      key: "overTime",
      width: 150,
    },
    {
      title: t("notes") /**备注 */,
      dataIndex: "notes",
      key: "notes",
      width: 400,
      align: "center",
      render: (_, item: any) =>
        JSON.parse(item.notes ? item.notes : "[]").map((n: any) => {
          return (
            <Row>
              <Col>
                <a>{`${n.time}：${n.info}`}</a>
              </Col>
            </Row>
          );
        }),
    },
    {
      title: t("describe") /**描述 */,
      dataIndex: "describe",
      key: "describe",
      width: 400,
    },
    {
      title: t("QkOmYwne") /**操作 */,
      key: "aaaa",
      width: 150,
      fixed: "right",
      align: "center",
      render: (_, item) => (
        <Space
          style={{
            visibility: item.userid === currentUser?.id ? "visible" : "hidden",
          }}
        >
          <Button
            size="small"
            onClick={() => {
              setShowEditDialog({ isShow: true, data: item });
            }}
          >
            {t("wXpnewYo") /**编辑 */}
          </Button>
          <Popconfirm
            title={t("DeleteConfirmation") /**删除确认 */}
            onConfirm={async () => {
              const [error] = await deleteItem(item.id);
              if (error) {
                antdUtils.message?.error(error);
              } else {
                getData(pagination.current ? pagination.current : 1);
              }
            }}
            okText={t("confirm") /**确定 */}
            cancelText={t("cancel") /**取消 */}
          >
            <Button size="small" type="dashed" danger>
              {t("HJYhipnp") /**删除 */}
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <Flex ref={ref} vertical>
      <Row align="middle">
        <Col>
          <p>{`${t("project") /**项目 */}: ${pData.name}`}</p>
        </Col>
        <Col offset={1}>
          <Button
            type="primary"
            onClick={() => {
              setShowNewDialog(true);
            }}
          >
            {t("VjwnJLPY") /**新建 */}
          </Button>
        </Col>
        <Col offset={1}>
          <Button
            type="primary"
            onClick={() => {
              navigate(`/my/planList/timenode/${pData.id}`);
            }}
          >
            {t("ImportantTimeNodes") /**重要时间节点 */}
          </Button>
        </Col>
      </Row>
      <br />
      <Row>
        <Col>
          <Form
            form={form}
            onFinish={onSearch}
            layout="inline"
            style={{ border: "1px solid rgb(59 130 246)", padding: "5px" }}
          >
            <Form.Item name="userid" label="负责人">
              <Select
                style={{ width: 100 }}
                onChange={() => {
                  setPagination((old) => {
                    old.current = 1;
                    old.pageSize = 8;
                    form.submit();
                  });
                }}
                options={allUsers}
              />
            </Form.Item>
            <Form.Item name="state" label="状态">
              <Select
                style={{ width: 100 }}
                onChange={() => {
                  setPagination((old) => {
                    old.current = 1;
                    old.pageSize = 8;
                    form.submit();
                  });
                }}
                options={[
                  { value: "0", label: "暂停" },
                  { value: "1", label: "执行中" },
                  { value: "2", label: "已完成" },
                ]}
              />
            </Form.Item>
            <Form.Item name="time" label="开始时间">
              <DatePicker.RangePicker
                format="YYYY-MM-DD"
                onChange={() => {
                  setPagination((old) => {
                    old.current = 1;
                    old.pageSize = 8;
                    form.submit();
                  });
                }}
              />
            </Form.Item>
            <Form.Item>
              <Button
                onClick={() => {
                  form.resetFields();
                  setPagination((old) => {
                    old.current = 1;
                    old.pageSize = 8;
                    form.submit();
                  });
                }}
              >
                {t("Restoration") /**复原 */}
              </Button>
            </Form.Item>
          </Form>
        </Col>
      </Row>
      <br />
      <Table
        rowKey={"id"}
        pagination={pagination}
        onChange={tabChangeHandle}
        columns={columns()}
        scroll={{ x: "100%", y: 600 }}
        dataSource={myList}
      />
      <EditDialog
        setShowEditDialog={setShowEditDialog}
        showEditDialog={showEditDialog}
        onSave={(data: any) => {
          setMyList((old) => {
            const index = old.findIndex((e) => e.id === data.id);
            if (index != -1) {
              old[index] = data;
            }
          });
        }}
      />
      <NewDialog
        setShowNewDialog={setShowNewDialog}
        showNewDialog={showNewDialog}
        projectid={pData.id}
        onSave={(data: any) => {
          setMyList((old) => {
            old.unshift(data);
          });
        }}
      />
    </Flex>
  );
};

export default MyProjectPlan;

const getPlanState = (state: string) => {
  let name = "";
  switch (state) {
    case "0":
      name = "暂停";
      break;
    case "1":
      name = "执行中";
      break;
    case "2":
      name = "已完成";
      break;
  }
  return name;
};
